package com.superhelper.app.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.superhelper.common.utils.HttpClientHelper;
import com.superhelper.common.utils.JsonHelper;

/**
 * 聚合短信接口
 * 
 * 
 */
@Service
public class JHSmsHandler {
	private final static Logger LOG = LoggerFactory
			.getLogger(JHSmsHandler.class);
	@Autowired
	private HttpClientHelper httpClient;
	@Value("${sms.app_key}")
	private String key;
	@Value("${sms.url}")
	private String host;
	private final String SEND_TEMPLATE = "%s/send?mobile=%s&tpl_id=%s&tpl_value=%s&key=%s";

	public boolean send(String phone, String tpl_id, String tpl_value) {
		String var = "";
		try {
			var = URLEncoder.encode(tpl_value, "utf-8");
		} catch (UnsupportedEncodingException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		String url = String
				.format(SEND_TEMPLATE, host, phone, tpl_id, var, key);
		LOG.info("send phone:{},tpl_id:{},url:{}", phone, tpl_id, url);
		String resp = null;
		try {
			resp = httpClient.doGet(url);
		} catch (Exception e) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e1) {
			}
			LOG.info("send retry phone:{}", phone);
			// 重试一次
			try {
				resp = httpClient.doGet(url);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
			}
		}
		LOG.info("send phone:{} response:{}", phone, resp);
		if (StringUtils.isBlank(resp)) {
			return false;
		}
		@SuppressWarnings("unchecked")
		Map<String, Object> data = JsonHelper.fromJson(resp, Map.class);
		if ((Integer) data.get("error_code") != 0) {
			return false;
		} else {
			return true;
		}
	}
}
